public class Solution61 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head==null){
            return null;
        }
        ListNode n=head;
        int len=0;
        ListNode last=new ListNode();
        while (n!=null){
            last=n;
            n=n.next;
            len++;
        }
        k=k%len;
        if (k==0){
            return head;
        }
        last.next=head;
        n=head;
        for (int i=0;i<len-k-1;i++){
            n=n.next;
        }
        ListNode ans=n.next;
        n.next=null;
        return ans;
    }

    public static void main(String[] args) {
        ListNode listNode=new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5)))));
        System.out.println(new Solution61().rotateRight(listNode,2).val);
    }
}
